'use client'

import React, { Suspense, useState } from 'react'
import { trpc } from '@/lib/trpc'
import { ErrorBoundary } from 'react-error-boundary'
import { Button } from '@/components/ui/button'
import { CopyCheckIcon, CopyIcon, Globe2Icon, ImagePlusIcon, LockIcon, MoreVerticalIcon, RotateCcwIcon, SparklesIcon, TrashIcon } from 'lucide-react'
import { useForm } from 'react-hook-form'
import { zodResolver } from "@hookform/resolvers/zod"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select"

import { z } from 'zod'
import { videoInsertSchema } from '@/db/schema'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { toast } from 'sonner'
import VideoPlayer from '@/modules/videos/ui/components/video-player'
import Link from 'next/link'
import { snakeCaseTotitle } from '@/lib/utils'
import { useRouter } from 'next/navigation'
import Image from 'next/image'
import ThumbnailUploadModal from '../ui/components/thumbnail-upload-modal'
import { Skeleton } from '@/components/ui/skeleton'

interface FormSectionProps {
    videoId: string
}

export function FormSectionSuspense({ videoId }: FormSectionProps) {
    const router = useRouter()
    const utils = trpc.useUtils()

    const [isThumbnailUploadModalOpen, setIsThumbnailUploadModalOpen] = useState(false)

    const [video] = trpc.studio.getOne.useSuspenseQuery({ id: videoId })
    const [categories] = trpc.categories.getMany.useSuspenseQuery()

    const update = trpc.videos.update.useMutation({
        onSuccess: () => {
            toast.success('Edit video success')
            utils.studio.getMany.invalidate()
            utils.studio.getOne.invalidate()
        },
        onError: (err) => {
            toast.error(err.message)
        }
    })

    const remove = trpc.videos.remove.useMutation({
        onSuccess: () => {
            toast.success('Remove video success')
            utils.studio.getMany.invalidate()
            router.push('/studio')
        },
        onError: (err) => {
            toast.error(err.message)
        }
    })

    const restoreThumbnail = trpc.videos.restoreThumbnail.useMutation({
        onSuccess: () => {
            toast.success('RestoreThumbnail success')
            utils.studio.getMany.invalidate()
            utils.studio.getOne.invalidate()
        },
        onError: (err) => {
            toast.error(err.message)
        }
    })

    const form = useForm<z.infer<typeof videoInsertSchema>>({
        resolver: zodResolver(videoInsertSchema),
        defaultValues: video
    })

    const onSubmit = async (data: z.infer<typeof videoInsertSchema>) => {
        update.mutate({
            id: videoId,
            ...data
        })
    }

    const fullUrl = `${process.env.VERCEL_URL || 'http://localhost:3000'}/videos/${videoId}`
    const [isCopied, setIsCopied] = useState(false)

    const onCopy = () => {
        navigator.clipboard.writeText(fullUrl)
        setIsCopied(true)
        setTimeout(() => {
            setIsCopied(false)
        }, 2000)
    }

    return (
        <>
            <ThumbnailUploadModal videoId={videoId} open={isThumbnailUploadModalOpen} onOpenChange={setIsThumbnailUploadModalOpen} />
            <Form {...form}>
                <form onSubmit={form.handleSubmit(onSubmit)} >
                    <div className='flex items-center justify-between mb-6'>
                        <div>
                            <h1 className='text-2xl font-bold'>Video details</h1>
                            <p className='text-xs text-muted-foreground'>Manage your video details</p>
                        </div>
                        <div className='flex items-center gap-x-2'>
                            <Button disabled={update.isPending} type="submit">Save</Button>
                            <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                    <Button variant="ghost" size="icon">
                                        <MoreVerticalIcon />
                                    </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent>
                                    <DropdownMenuItem onClick={() => remove.mutate({ id: videoId })}>
                                        <TrashIcon className='size-4 mr-2' />
                                        Delete
                                    </DropdownMenuItem>
                                </DropdownMenuContent>
                            </DropdownMenu>
                        </div>
                    </div>
                    <div className='grid grid-cols-1 lg:grid-cols-5 gap-6'>
                        <div className='space-y-8 lg:col-span-3'>
                            <FormField control={form.control} name='title' render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Title</FormLabel>
                                    <FormControl>
                                        <Input placeholder="add a title to your video" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )} />
                            <FormField control={form.control} name='description' render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Description</FormLabel>
                                    <FormControl>
                                        <Textarea placeholder="add a description to your video" {...field} value={field.value ?? ''} className='resize-none pr-10  h-[200px]'></Textarea>
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )} />

                            <FormField control={form.control} name="thumbnailUrl" render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Thumbnail URL</FormLabel>
                                    <FormControl>
                                        <div className='p-0.5 border border-dashed border-neutral-400 relative h-[84px] w-[153px] group'>
                                            <Image fill className='object-cover' src={video.thumbnailUrl ?? '/placeholder.svg'} alt={video.title ?? 'thumbnail'} />

                                            <DropdownMenu>
                                                <DropdownMenuTrigger asChild>
                                                    <Button type='button' size="icon" className='bg-black/50  absolute top-1 right-1  rounded-full opacity-100 md:opacity-0 group-hover:opacity-100 duration-300 size-7'>
                                                        <MoreVerticalIcon className='size-4 text-white' />
                                                    </Button>
                                                </DropdownMenuTrigger>
                                                <DropdownMenuContent align='start' side='right'>
                                                    <DropdownMenuItem onClick={() => setIsThumbnailUploadModalOpen(true)}>
                                                        <ImagePlusIcon className='size-4 mr-1' />
                                                        Change
                                                    </DropdownMenuItem>
                                                    <DropdownMenuItem onClick={() => restoreThumbnail.mutate({ id: videoId })}>
                                                        <RotateCcwIcon className='size-4 mr-1' />
                                                        Restore
                                                    </DropdownMenuItem>
                                                </DropdownMenuContent>
                                            </DropdownMenu>
                                        </div>
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )} />

                            <FormField control={form.control} name='categoryId' render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Category</FormLabel>
                                    <Select onValueChange={field.onChange} defaultValue={field.value ?? undefined}>
                                        <FormControl>
                                            <SelectTrigger className='w-full'>
                                                <SelectValue placeholder='Select a category'></SelectValue>
                                            </SelectTrigger>
                                        </FormControl>
                                        <SelectContent>
                                            {categories.map((category) => (
                                                <SelectItem key={category.id} value={category.id}>{category.name}</SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                    <FormMessage />
                                </FormItem>
                            )} />
                        </div>

                        <div className='flex flex-col gap-y-2 lg:col-span-2 bg-[#f7f7f7] rounded-xl overflow-hidden'>
                            <div className='flex felx-col gap-4  '>
                                <div className='w-full aspect-video overflow-hidden relative'>
                                    <VideoPlayer playbackId={video.muxPlaybackId} thumbnailUrl={video.thumbnailUrl} />
                                </div>
                            </div>
                            <div className='p-4 flex flex-col gap-y-2'>
                                <div className='flex justify-between items-center gap-x-2'>
                                    <div className='flex flex-col gap-y-1'>
                                        <p className='text-muted-foreground text-xs'>
                                            Video Link
                                        </p>
                                        <div className='flex items-center gap-x-2'>
                                            <Link href={`videos/${video.id}`} >
                                                <p className='line-clamp-1 text-sm text-blue-500'>{fullUrl}</p>
                                            </Link>
                                            <Button type='button' variant="ghost" size="icon" className='shrink-0' disabled={isCopied} onClick={onCopy}>
                                                {isCopied ? <CopyCheckIcon /> : <CopyIcon />}
                                            </Button>
                                        </div>
                                    </div>
                                </div>

                                <div className='flex justify-between items-center'>
                                    <div className='flex flex-col gap-y-1'>
                                        <p className='text-muted-foreground text-xs'>
                                            Video Status
                                        </p>
                                        <p className='text-sm'>
                                            {snakeCaseTotitle(video.muxStatus || 'preparing')}
                                        </p>
                                    </div>
                                </div>

                                <div className='flex justify-between items-center'>
                                    <div className='flex flex-col gap-y-1'>
                                        <p className='text-muted-foreground text-xs'>
                                            Subtitles Status
                                        </p>
                                        <p className='text-sm'>
                                            {snakeCaseTotitle(video.muxTrackStatus || 'preparing')}
                                        </p>
                                    </div>
                                </div>
                            </div>

                            <div className='p-4'>
                                <FormField control={form.control} name='visibility' render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Visibility</FormLabel>
                                        <Select onValueChange={field.onChange} defaultValue={field.value ?? undefined}>
                                            <FormControl>
                                                <SelectTrigger className='w-full'>
                                                    <SelectValue placeholder='Select a visibility'></SelectValue>
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                <SelectItem value="public">
                                                    <Globe2Icon className='size-4 mr-2' />
                                                    Public</SelectItem>
                                                <SelectItem value="private">
                                                    <LockIcon className='size-4 mr-2' />
                                                    Private</SelectItem>
                                            </SelectContent>
                                        </Select>
                                        <FormMessage />
                                    </FormItem>
                                )} />
                            </div>
                        </div>
                    </div>
                </form>
            </Form>
        </>
    )
}

const FormSectionSkeleton = () => {
    return (
        <div>
            <div className='flex items-center justify-between mb-6'>
                <div className='space-y-1'>
                    <Skeleton className='h-7 w-32' />
                    <Skeleton className='h-4 w-40' />
                </div>
                <Skeleton className='h-9 w-24' />
            </div>
            <div className='grid grid-cols-1 lg:grid-cols-5 gap-6'>
                <div className='space-y-8 lg:col-span-3'>
                    <div className='space-y-1'>
                        <Skeleton className='h-5 w-16' />
                        <Skeleton className='h-10 w-full' />
                    </div>
                    <div className='space-y-1'>
                        <Skeleton className='h-5 w-24' />
                        <Skeleton className='h-[220px] w-full' />
                    </div>
                    <div className='space-y-1'>
                        <Skeleton className='h-5 w-20' />
                        <Skeleton className='h-[84px] w-[153px]' />
                    </div>
                    <div className='space-y-1'>
                        <Skeleton className='h-5 w-20' />
                        <Skeleton className='h-10 w-full' />
                    </div>
                </div>
                <div className='flex flex-col gap-y-4 lg:col-span-2'>
                    <div className='flex felx-col gap-4'>
                        <Skeleton className='w-full aspect-auto h-[250px]' />
                    </div>
                    <div className='px-4 py-4 space-y-4'>
                        <div className='space-y-2'>
                            <Skeleton className='h-4 w-20' />
                            <Skeleton className='h-5 w-full' />
                        </div>
                        <div className='space-y-2'>
                            <Skeleton className='h-4 w-24' />
                            <Skeleton className='h-5 w-32' />
                        </div>
                        <div className='space-y-2'>
                            <Skeleton className='h-4 w-24' />
                            <Skeleton className='h-5 w-32' />
                        </div>
                    </div>
                    <div className='space-y-4'>
                        <Skeleton className='h-5 w-20' />
                        <Skeleton className='h-10 w-full' />
                    </div>
                </div>
            </div>
        </div>
    )
}

export default function FormSection({ videoId }: FormSectionProps) {
    return (
        <Suspense fallback={<FormSectionSkeleton />}>
            <ErrorBoundary fallbackRender={({ error }) => <p>error:{error.message}</p>}>
                <FormSectionSuspense videoId={videoId} />
            </ErrorBoundary>
        </Suspense>

    )
}